package com.demo.dubborpc.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author gy
 * @date 2022/8/7
 */
public class NettyClient {

    // 创建线程池
    private static final ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime()
            .availableProcessors());

    private int count = 0 ;

    private static NettyClientHandler client;

    public Object getBean(final Class<?> serviceClass,final String protocolHead){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class<?>[]{serviceClass},(proxy,method,args) -> {
                    System.out.println("开始创建代理对象~~~,第" + (++count) + "次创建");
                    if (client == null){
                        initClient();
                    }
                    // 设置要发给服务器端的信息
                    // protocolHead 协议头 ，args[0] 就是客户端调用 api时传入的param
                    client.setRequest(protocolHead + args[0]);

                    // 将  NettyClientHandler 提交到线程池里面执行，并得到结果
                    return executor.submit(client).get();
                });
    }

    // 初始化客户端
    private static void initClient() throws InterruptedException {
        client = new NettyClientHandler();
        // 创建 EventLoopGroup
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringDecoder())
                                .addLast(new StringEncoder())
                                .addLast(client);
                    }
                });
        bootstrap.connect("127.0.0.1",7000).sync();
    }

}
